﻿using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

	/// 洗牌
	public void DealCards()
	{
		//洗牌
		Deck.Instance.Shuffle();

		//发牌
		CharacterType currentCharacter = CharacterType.Player;
		for (int i = 0; i < 50 * 2; i++)
		{
			if (currentCharacter == CharacterType.Desk)
			{
				currentCharacter = CharacterType.Player;
			}
			DealTo(currentCharacter);
			currentCharacter++;
		}

		for (int i = 0; i < 8; i++)
		{
			DealTo(CharacterType.Desk);
		}

		UIPlayers.Instance.player.GetComponent<UIPlayerManager>().CreateCards();
		UIPlayers.Instance.playerLeft.GetComponent<UIPlayerManager>().CreateCards();
		UIPlayers.Instance.playerRight.GetComponent<UIPlayerManager>().CreateCards();
		UIPlayers.Instance.playerOpposite.GetComponent<UIPlayerManager>().CreateCards();
		UIPlayers.Instance.desk.GetComponent<UIPlayerManager> ().CreateCards ();
	}

	/// 发牌
	void DealTo(CharacterType person)
	{
		if (person == CharacterType.Desk)
		{
			Card movedCard = Deck.Instance.Deal();
			DeskCardsCache.Instance.AddCard(movedCard);
		}
		else
		{
			GameObject playerObj = GameObject.Find(person.ToString());
			HandCards cards = playerObj.GetComponent<HandCards>();

			Card movedCard = Deck.Instance.Deal();
			cards.AddCard(movedCard);
		}
	}

	/// <summary>
	/// 获取指定数组的权值
	/// </summary>
	/// <param name="cards"></param>
	/// <param name="rule"></param>
	/// <returns></returns>
	public static int GetWeight(Card[] cards, CardsType rule)
	{
		int totalWeight = 0;
		if (rule == CardsType.ThreeAndOne || rule == CardsType.ThreeAndTwo)
		{
			for (int i = 0; i < cards.Length; i++)
			{
				if (i < cards.Length - 2)
				{
					if (cards[i].GetCardWeight == cards[i + 1].GetCardWeight &&
						cards[i].GetCardWeight == cards[i + 2].GetCardWeight)
					{
						totalWeight += (int)cards[i].GetCardWeight;
						totalWeight *= 3;
						break;
					}
				}
			}
		}
		else
		{
			for (int i = 0; i < cards.Length; i++)
			{
				totalWeight += (int)cards[i].GetCardWeight;
			}
		}

		return totalWeight;
	}

	public void GameOver()
	{
		
	}
}
